//
//  UIColor+Extension.swift
//  CustomWeiBo
//
//  Created by laiqiang on 21/5/10.
//  Copyright © 2021年 laiqiang. All rights reserved.
//

import Foundation

extension UIColor {

    var randomColor: UIColor{
        
        let red = CGFloat(arc4random_uniform(255))
        let gree = CGFloat(arc4random_uniform(255))
        let blue = CGFloat(arc4random_uniform(255))
        return UIColor.init(red: red/255.0, green: gree/255.0, blue: blue/255.0, alpha: 1.0)
    }
    
    //class 定义"类对象"属性
    var WBPinkColor: UIColor{

        return UIColor.init(red:255/255.0, green:72/255.0, blue:145/255.0, alpha: 1.0)
    }
    
    class func colorWithaHex(hexStr:String)-> UIColor {
        
        // Hex String -> UIColor
        let hexString = hexStr.trimmingCharacters(in: .whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        if hexString.hasPrefix("#") {//带＃好的，否者是0x格式的
            
            scanner.scanLocation = 1
        }
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)//中转 类，获取计算的color值
        let mask = 0x0000FF
        let r = Int(color >> 16) & mask//mask，记录color值偏移后的数据
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        
        return UIColor(red: red, green: green, blue: blue, alpha: 1)
    }
    
    //6位的数值直接获取颜色0x f6f6f6,前缀0x，#去除
    class func colorWithbHex(hex: UInt32)-> UIColor {
        
        let r: CGFloat = CGFloat((hex & 0xFF000000) >> 24) / 255.0
        let g: CGFloat = CGFloat((hex & 0x00FF0000) >> 16) / 255.0
        let b: CGFloat = CGFloat((hex & 0x0000FF00) >> 8) / 255.0
        let a: CGFloat = CGFloat(hex & 0x000000FF) / 255.0
        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
    
    /// 创建一张纯色的图片的方法
    func toImage(size: CGSize) -> UIImage {
        UIGraphicsBeginImageContext(size);
        let context = UIGraphicsGetCurrentContext();
        context?.setFillColor(self.cgColor)
        context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image!;
    }

}
